import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 导入原始动态路由表
import { asyncRoutes } from './router/asyncRoutes'

const { default: router } = require('./router')
const { default: store } = require('./store')
nProgress.configure({
  showSpinner: false
})
const whiteList = ['/login', '/404']
// 处理一级路由权限数据
// function getFirstRoutePerms(permsArr) {
//   const newArr = permsArr.map(item => {
//     return item.split(':')[0]
//   })
//   return [...new Set(newArr)]
// }
function getFirstRoutePerms(permsArr) {
  const newArr = []
  for (let i = 0; i < permsArr.length; i++) {
    const item = permsArr[i].split(':')[0]
    if (newArr.indexOf(item) === -1) {
      newArr.push(item)
    }
  }
  return newArr
}
// 处理二级路由权限数据
// function getSecondRoutePerms(permsArr) {
//   const newArr = permsArr.map(item => {
//     const arr = item.split(':')
//     return `${arr[0]}:${arr[1]}`
//   })
//   return [...new Set(newArr)]
// }
function getSecondRoutePerms(permsArr) {
  return permsArr.filter((item, index) => {
    const arr = item.split(':')
    const newItem = `${arr[0]}:${arr[1]}`
    return permsArr.indexOf(newItem) === index
  })
}
// 根据权限标识过滤路由表
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
}
router.beforeEach(async(to, from, next) => {
  nProgress.start()
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      nProgress.done()
    } else {
      // 获取用户信息
      if (!store.state.user.profile.id) {
      // 获取原始权限列表
        const permissions = await store.dispatch('user/getProfile')
        // console.log(permissions)
        // 2. 把后端的权限数组格式化成我们自己的俩个权限数据
        console.log('当前的权限数据为:', permissions)
        const firstRoutePerms = getFirstRoutePerms(permissions)
        console.log(firstRoutePerms)
        const secondRoutePerms = getSecondRoutePerms(permissions)
        console.log(secondRoutePerms)
        // 3. 根据权限标识 过滤筛选 动态路由表 最终得到有资格显示到左侧的所有路由表
        const perRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
        console.log('最终路由表', perRoutes)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})
router.afterEach(() => {
  nProgress.done()
})
